﻿using System;
using System.Windows.Forms;

namespace PwManager
{
    public partial class FormDetail : Form
    {
        Form1 mailForm;
        public FormDetail(Form1 from1)
        {
            InitializeComponent();
            mailForm = from1;
            Text = "New";
        }

        public FormDetail(StrongBox box, Form1 from1)
        {
            InitializeComponent();
            mailForm = from1;
            Text = "Edit";

            lbID.Text = box.ID.ToString();
            txtTitle.Text = box.Title;
            txtRemark.Text = box.Remark;
            txtAccount.Text = box.Account;
            txtPwd.Text = box.Pwd;
            cmbRegisterBy.Text = box.RegisterBy;
            txtRegisterByAccount.Text = box.RegisterByAccount;
        }


        private void btnReset_Click(object sender, EventArgs e)
        {
            txtTitle.Text = "";
            txtRemark.Text = "";
            txtAccount.Text = "";
            txtPwd.Text = "";
            cmbRegisterBy.Text = "";
            txtRegisterByAccount.Text = "";
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (ValiteInput())
            {
                var box = new StrongBox
                {
                    ID = Convert.ToInt32(lbID.Text),
                    Title = txtTitle.Text.Trim(),
                    Account = txtAccount.Text.Trim(),
                    Pwd = EncryptHelper.Encrypt(txtPwd.Text.Trim()),
                    Remark = txtRemark.Text.Trim(),
                    RegisterBy = cmbRegisterBy.Text,
                    RegisterByAccount = txtRegisterByAccount.Text.Trim(),
                };
                if (Save(box) == 1)
                {
                    MessageBox.Show("操作成功");
                    mailForm.DataBind();
                    Close();
                }
                else
                    MessageBox.Show("操作失败");
            }
        }

        bool ValiteInput()
        {
            if (string.IsNullOrWhiteSpace(txtTitle.Text))
            {
                lbTitleMsg.Text = "*必填项";
                return false;
            }
            lbTitleMsg.Text = "*";

            if (string.IsNullOrWhiteSpace(txtAccount.Text))
            {
                lbAccountMsg.Text = "*必填项";
                return false;
            }
            lbAccountMsg.Text = "*";

            if (string.IsNullOrWhiteSpace(txtPwd.Text))
            {
                lbPwdMsg.Text = "*必填项";
                return false;
            }
            lbPwdMsg.Text = "*";

            return true;
        }

        int Save(StrongBox box)
        {
            if (box.ID > 0)
                return StrongBoxCore.Edit(box);
            return StrongBoxCore.Add(box);
        }
    }
}
